# -*- coding: utf-8 -*-
from repoze.bfg.location import lineage
from z3c.pt.pagetemplate import ViewPageTemplateFile
from zope.component import getMultiAdapter
from zope.location import LocationIterator

from pargo.interfaces import IContent, ISite
from pargo.utils import pretty_title_or_id
from pargo.viewlet.viewlet import PageTemplateViewlet


class BreadcrumbsViewlet(PageTemplateViewlet):
    """
    Breadcrumbs.
    """
    template = ViewPageTemplateFile('templates/breadcrumbs.pt')

    def _crumb(self, obj):
        """
        Basic object information.
        """
        result = {
            'id': obj.__name__,
            'title': pretty_title_or_id(obj),
            'url': getMultiAdapter((obj, self.request), name='absolute_url')()
            }
            
        return result

    def get_breadcrumbs(self):
        """
        List of nodes with names.
        """
        l = [self._crumb(i) for i in lineage(self.context) if IContent.providedBy(i)]
        l.reverse()
        return l


class TopMenuViewlet(PageTemplateViewlet):
    """
    Top menu.
    """
    template = ViewPageTemplateFile('templates/top-menu.pt')

    def _get_site(self):
        """
        Get site object.
        """
        for item in LocationIterator(self.context):
            if ISite.providedBy(item):
                return item
        
        return None
    
    def _menu_item(self, obj):
        """
        Basic object information.
        """
        result = {
            'id': obj.__name__,
            'title': pretty_title_or_id(obj),
            'url': getMultiAdapter((obj, self.request), name='absolute_url')()
            }
            
        return result
    
    def get_menu_items(self):
        """
        Return content of menu.
        """
        site = self._get_site()
        result = [self._menu_item(obj) for obj in site.values()]
        return result
